package com.zhuqi.redis.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuqi.domain.ChatMessageDo;
import com.zhuqi.service.ChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * <p> Redis 消息监听 </p>
 * @author zhuqi
 * @since 2023/4/13 9:43
 * ps: 后面改造为消息中间件
 */
@Component
@Slf4j
public class Subscriber implements MessageListener {

	@Autowired
	@Qualifier(value = "pubSubStrRedisTemplate")
	private RedisTemplate<String,String> redisTemplate;

	@Autowired
	private ChatMessageService chatMessageService;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		RedisSerializer<?> keySerializer = redisTemplate.getKeySerializer();
		RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();
		String key = (String) keySerializer.deserialize(message.getChannel());
		String value = (String) valueSerializer.deserialize(message.getBody());
		log.info("消息 key:{}, value:{}", key, value);

		JSONObject jsonObject = JSON.parseObject(value);

		// 获取存储的消息类型
		Integer redisMessageType = jsonObject.getInteger("redisMessageType");

		// 保存聊天消息
		if (redisMessageType == 0) {
			ChatMessageDo chatMessageDo = JSON.parseObject(value, ChatMessageDo.class);
			chatMessageService.insert(chatMessageDo);
		}
	}
}